package cn.turboinfo.fuyang.api.gateway.admin.controller.login;

import cn.turboinfo.fuyang.api.entity.admin.pojo.captcha.Captcha;
import cn.turboinfo.fuyang.api.gateway.admin.constant.AdminConstants;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;

@RequiredArgsConstructor
@RestController
@RequestMapping("/kaptcha")
public class KaptchaController {

    private final DefaultKaptcha defaultKaptcha;

    @GetMapping("/image")
    public void imageCode(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
        try {
            // 生产验证码字符串并保存到session中
            String createText = defaultKaptcha.createText();
            request.getSession().setAttribute(AdminConstants.AttrDefaultCaptcha, new Captcha(createText));
            // 使用生成的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
            BufferedImage challenge = defaultKaptcha.createImage(createText);

            ImageIO.write(challenge, "jpg", jpegOutputStream);
        } catch (IllegalArgumentException e) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        // 定义response输出类型为image/jpeg类型，使用response输出流输出图片的byte数组
        byte[] captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
        response.setHeader("Cache-Control", "no-store");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");
        ServletOutputStream responseOutputStream = response.getOutputStream();
        responseOutputStream.write(captchaChallengeAsJpeg);
        responseOutputStream.flush();
        responseOutputStream.close();
    }

    @GetMapping("/check")
    public boolean checkVerificationCode(@RequestParam(value = "captcha") String captcha, HttpServletRequest request) {
        Captcha captchaInSession = (Captcha) request.getSession().getAttribute(AdminConstants.AttrDefaultCaptcha);
        if (captchaInSession == null) {
            return false;
        }
        return !captchaInSession.isExpired() && captchaInSession.getCode().equals(captcha);
    }
}
